<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="软件类型" prop="softwareType">
        <el-select v-model="formData.softwareType" placeholder="请选择软件类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_SOFTWARE_VERSION_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学校" prop="schoolId">
        <el-select
          v-model="formData.schoolId"
          placeholder="请选择学校"
          filterable
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.id"
            :label="item.schoolName + '-' + item.tenantName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="平台ID" prop="platformId">
        <el-input v-model.trim="formData.platformId" placeholder="请输入平台ID" maxLength="50" />
      </el-form-item>
      <el-form-item label="状态" prop="status" placeholder="请选择状态">
        <el-select v-model="formData.status">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_SOFTWARE_VERSION_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="更新状态" prop="updateStatus" placeholder="请选择更新状态">
        <el-select v-model="formData.updateStatus">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_SOFTWARE_VERSION_UPDATE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="md5值" prop="apkMd5">
        <el-input v-model.trim="formData.apkMd5" placeholder="请输入md5值" maxLength="50" />
      </el-form-item>
      <!-- <el-form-item label="文件大小" prop="apkSize">
        <el-input v-model.trim="formData.apkSize" placeholder="请输入文件大小" maxLength="50"/>
      </el-form-item>
      <el-form-item label="下载URL" prop="downloadUrl">
        <el-input v-model.trim="formData.downloadUrl" placeholder="请输入下载URL" maxLength="50"/>
      </el-form-item> -->
      <el-form-item label="版本编码" prop="versionCode">
        <el-input v-model.trim="formData.versionCode" placeholder="请输入版本编码" maxLength="50" />
      </el-form-item>
      <el-form-item label="版本名称" prop="versionName">
        <el-input v-model.trim="formData.versionName" placeholder="请输入版本名称" maxLength="50" />
      </el-form-item>
      <el-form-item label="修改内容">
        <el-input
          v-model.trim="formData.modifyContent"
          type="textarea"
          :rows="2"
          :maxlength="1000"
          show-word-limit
          placeholder="请输入选项文本"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as SoftwareVersionApi from '@/api/system/softwareVersion'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as BaseSchoolApi from '@/api/cmis/school'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  schoolId: undefined,
  platformId: undefined,
  softwareType: undefined,
  status: undefined,
  apkMd5: undefined,
  apkSize: undefined,
  downloadUrl: undefined,
  modifyContent: undefined,
  updateStatus: undefined,
  versionCode: undefined,
  versionName: undefined
})
const formRules = reactive({
  softwareType: [{ required: true, message: '软件类型不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态 1正常 2停用不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SoftwareVersionApi.getSoftwareVersion(id)
    } finally {
      formLoading.value = false
    }
  }
  getSchoolList()
  // 表单放在最后才展示，防止父组件传值不到给子组件
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SoftwareVersionApi.SoftwareVersionVO
    if (formType.value === 'create') {
      await SoftwareVersionApi.createSoftwareVersion(data)
      message.success(t('common.createSuccess'))
    } else {
      await SoftwareVersionApi.updateSoftwareVersion(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 查询学校列表[忽略租户] */
const schoolList = ref<BaseSchoolApi.BaseSchoolVO[]>([])
const getSchoolList = async () => {
  try {
    const data = await BaseSchoolApi.selectAllBaseSchoolList({})
    schoolList.value = data
  } catch {}
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    schoolId: undefined,
    platformId: undefined,
    softwareType: undefined,
    status: undefined,
    apkMd5: undefined,
    apkSize: undefined,
    downloadUrl: undefined,
    modifyContent: undefined,
    updateStatus: undefined,
    versionCode: undefined,
    versionName: undefined
  }
  formRef.value?.resetFields()
}
</script>
